<?php

class Bill extends Base_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Bill_model', 'bill');
        $this->load->model('Express_model', 'express');
    }

    public function handle()
    {
        $this->bill->getHandle();
    }

    public function index()
    {
        $per_page            = $this->input->get('per_page') ? $this->input->get('per_page') : 0;
        $filter['keyword']   = $this->input->get('keyword') ? $this->input->get('keyword') : '';
        $filter['endtime']   = $this->input->get('endtime') ? $this->input->get('endtime') : '';
        $filter['starttime'] = $this->input->get('starttime') ? $this->input->get('starttime') : '';
        $limit               = 20;
        $total_rows          = $this->bill->getCnt($filter);
        $base_url            = '/bill/index?';
        if (!empty(array_filter($filter))) {
            http_build_query(array_filter($filter));
            $base_url = '/bill/index?' . http_build_query(array_filter($filter));
        }
        $page_links = $this->create_page_links($base_url, $total_rows, $limit);
        $billList   = $this->bill->getList(" * ", $per_page, $limit, $filter);
        $handleData = [];
        foreach ($billList as $bill) {
            $handleData[$bill['contract_number']]['money'][]                = $bill['number'] * $bill['unit_selling_price'];//价格
            $handleData[$bill['contract_number']]['purchase_total_price'][] = $bill['number'] * $bill['purchase_price'];//总价

        }

        foreach ($billList as $key => $bill) {
            $billList[$key]['money']                = number_format(array_sum($handleData[$bill['contract_number']]['money']), 2);
            $billList[$key]['purchase_total_price'] = number_format($bill['number'] * $bill['purchase_price'], 2); //采购总价
            $billList[$key]['total_purchase_cost']  = number_format(array_sum($handleData[$bill['contract_number']]['purchase_total_price']), 2);//采购总费用
            $billList[$key]['profit']               = number_format(array_sum($handleData[$bill['contract_number']]['money']) - array_sum($handleData[$bill['contract_number']]['purchase_total_price']), 2);//利润
            $billList[$key]['sales_price']          = number_format($bill['number'] * $bill['unit_selling_price'], 2);
        }
        //var_dump($handleData);
        //var_dump($billList);
        $data = array(
            'billList'   => $billList,
            'page_links' => $page_links,
            'handleData' => $handleData,
            'per_page'   => $per_page,
            'total_rows' => $total_rows,
            'starttime'  => $filter['starttime'],
            'endtime'    => $filter['endtime'],
            'keyword'    => $filter['keyword'],
        );
        $this->load->view('bill/index', $data);
    }

     public function addview()
    {
        $contract_number = $this->input->get("contract_number");
        if($contract_number){
            $recordInfo    = $this->bill->getRecordByContractNumber($contract_number, ' contract_number,signed_time,provider,contact,invoice,type,origin,customer_unit,order_number ')[0];
        }else{
            $recordInfo = $this->bill->getMaxContractNumber();
            $prefix = "BD";
            $max_len = 7;
            $number = (int)substr($recordInfo['contract_number'],strlen($prefix))+1;
            $fill_num = $max_len-strlen($number);
            $recordInfo['contract_number'] = str_pad($prefix,$fill_num,0).$number;
        }
        $view            = 'bill/add';
        $this->load->view($view, $recordInfo);
    }

    public function addexpressview()
    {
        $contract_number = $this->input->get("contract_number");
        $express_list    = $this->express->getList();
        $data            = [
            'express_list'    => $express_list,
            'contract_number' => $contract_number,
        ];
        $view            = 'bill/express';
        $this->load->view($view, $data);
    }

    public function editview()
    {
        $bill_id                  = $this->input->get('bill_id', true) ?? 0;
        $billInfo                 = $this->bill->getDetail($bill_id);
        $express_list             = $this->express->getList();
        $billInfo['express_list'] = $express_list;
        $view                     = 'bill/add';
        if ($billInfo['type'] == 2) {
            $view = 'bill/express';
        }
        $this->load->view($view, $billInfo);
    }

    public function detail()
    {
        $contract_number = $this->input->get("contract_number");
        $recordList      = $this->bill->getRecordByContractNumber($contract_number, " * ");
        $data            = [
            'recordList' => $recordList,
        ];
        $this->load->view('bill/detail', $data);
    }

    public function update()
    {
        try {
            $bill_id = $this->input->post('bill_id', true) ?? 0;

            $params['contract_number']    = $this->input->post('contract_number', true) ?? 3;
            $params['customer_unit']      = $this->input->post('customer_unit', true) ?? '';
            $params['order_number']       = $this->input->post('order_number', true) ?? 3;
            $params['signed_time']        = $this->input->post('signed_time', true) ?? 0;
            $params['piece_number']       = $this->input->post('piece_number', true) ?? '';
            $params['name']               = $this->input->post('name', true) ?? '';
            $params['number']             = $this->input->post('number', true) ?? 0;
            $params['unit_selling_price'] = $this->input->post('unit_selling_price', true) ?? 0;
            $params['purchase_price']     = $this->input->post('purchase_price', true) ?? 0;
            $params['provider']           = $this->input->post('provider', true) ?? '';
            $params['contact']            = $this->input->post('contact', true) ?? '';
            $params['invoice']            = $this->input->post('invoice', true) ?? 0;
            $params['origin']             = $this->input->post('origin', true) ?? 0;
            $params['remark']             = $this->input->post('remark', true) ?? '';
            $params['user_id']            = $_SESSION['adminUserInfo']['id'];
            if ($bill_id) {
                $params['create_time'] = date('Y-m-d H:i:s');
                $result                = $this->bill->edit($bill_id, $params);
                if (!$result) throw new RuntimeException("编辑失败");
            } else {
                $result = $this->bill->add($params);
                if (!$result) throw new RuntimeException("添加失败");
            }
            if (!$result) {
                $this->error("添加失败");
            }
            $this->success();
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

    }

    public function updateExpress()
    {
        try {
            $bill_id                   = $this->input->post('bill_id', true) ?? 0;
            $params['contract_number'] = $this->input->post('contract_number', true) ?? '';
            $params['number']          = $this->input->post('number', true) ?? 1;

            $params['provider']           = $this->input->post('provider', true) ?? '';
            $params['name']               = '运费';
            $params['unit_selling_price'] = $this->input->post('unit_selling_price', true) ?? 0;
            $params['purchase_price']     = $this->input->post('purchase_price', true) ?? 0;
            $params['remark']             = $this->input->post('remark', true) ?? '';
            $params['express_number']     = $this->input->post('express_number', true) ?? '';
            $params['user_id']            = $_SESSION['adminUserInfo']['id'];
            $params['type']               = 2;

            $fields                 = " signed_time, deliver_time, invoice, order_number, origin ";
            $recordInfo             = $this->bill->getRecordByContractNumber($params['contract_number'], $fields)[0];
            $params['signed_time']  = $recordInfo['signed_time'];
            $params['deliver_time'] = $recordInfo['deliver_time'];
            $params['invoice']      = $recordInfo['invoice'];
            $params['order_number'] = $recordInfo['order_number'];
            $params['origin']       = $recordInfo['origin'];
            if ($bill_id) {
                $params['create_time'] = date('Y-m-d H:i:s');
                $result                = $this->bill->edit($bill_id, $params);
                if (!$result) throw new RuntimeException("编辑失败");
            } else {
                $result = $this->bill->add($params);
                if (!$result) throw new RuntimeException("添加失败");
            }
            if (!$result) {
                $this->error("添加失败");
            }
            $this->success();
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

    }

    public function delete()
    {
        try {
            $bill_id = $this->input->post('bill_id', true) ?? 0;
            if (empty($bill_id)) {
                throw new InvalidArgumentException("id不能为空");
            }
            $result = $this->bill->delete($bill_id);
            if (!$result) {
                throw new RuntimeException("删除失败");
            }
            $this->success();
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    public function searchName(){
        try {
            $name = $this->input->get('billname', true) ?? 0;
            $type = $this->input->get('type', true) ?? 0;
            if (empty($name)) {
                $this->success();
            }
            $result = $this->bill->searchName(1,20,['name'=>$name,'type'=>$type]);
            $nameList = [];
            foreach($result as $row){
                $nameList[] = $row[$type];
            }
            $this->success($nameList);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    public function deliver()
    {
        try {
            $contract_number = $this->input->post('contract_number', true) ?? 0;
            if (empty($contract_number)) {
                throw new InvalidArgumentException("contract_number不能为空");
            }
            $result = $this->bill->deliver($contract_number);
            if (!$result) {
                throw new RuntimeException("设置失败");
            }
            $this->success();
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}
